import { app, shell, BrowserWindow, ipcMain } from 'electron'
import UDPServer from './udp.server'
import { jspack } from 'jspack'
import GPIOServer from './gpio.server'
import RS422Server from './rs422.server'
import TestServer from './test.server'
import FramePacker from './FramePacker'
import TestFramePacker from './TestFramePacker'



export default class NodeServer {
  public mainWindow: BrowserWindow
  private _udpServer: UDPServer
  private _framePacker: FramePacker
  private _gpioServer: GPIOServer
  private _rs422Server: RS422Server
  private _testServer: TestServer
  constructor(mainWindow) {
    this.mainWindow = mainWindow
    this._framePacker = new FramePacker(0xaa, 0xbb)
    this._testFramePacker = new TestFramePacker(0xcc, 0xcc)
    this._udpServer = new UDPServer(10010)

    const frameParser = (msg) => {
      const fmt = '>BBBBBBBBBBBBBB'
      const  acceptFields =  [
        'header',
        'cpu',
        'memory',
        'fpga',
        'nvram',
        'sync',
        'cpuNumber',
        'computer',
        'type',
        'param1',
        'param2',
        'cmd',
        'number',
        'state'
      ]
      const message =  jspack.Unpack(fmt, msg)

      return Object.fromEntries(acceptFields.map((key, index) => [key, message[index]]))
    }

    this._udpServer.on('message', (msg, rinfo) => {
      const message = frameParser(msg)
      if(message.cmd === 1) {
        // console.log('message', message)
        this.mainWindow.webContents.send('status', message)
      }
    })
  }

  create() {
    this._gpioServer = new GPIOServer(this._udpServer, this._framePacker)
    this._testServer = new TestServer(this._udpServer, this._framePacker)
    this._rs422Server = new RS422Server()
  }

  forwardMessage(channel, message) {
    this.mainWindow.webContents.send('status', message)
  }
}
